package com.ccn.kotlin_mvvm

import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.OnBackPressedCallback
import androidx.navigation.Navigation
import com.blankj.utilcode.util.ToastUtils
import com.ccn.jetpack_mvvm.base.viewmodel.BaseViewModel
import com.ccn.jetpack_mvvm.network.manager.NetState
import com.ccn.kotlin_mvvm.app.appViewModel
import com.ccn.kotlin_mvvm.app.base.BaseActivity
import com.ccn.kotlin_mvvm.databinding.ActivityMainBinding
import com.tencent.bugly.beta.Beta
import me.hgj.jetpackmvvm.demo.app.util.StatusBarUtil

class MainActivity : BaseActivity<BaseViewModel, ActivityMainBinding>() {

    var exitTime = 0L

    override fun layoutId(): Int = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        //进入首页检查更新 bugly不集成
//        Beta.checkUpgrade(false,false)
        onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    val nav = Navigation.findNavController(this@MainActivity, R.id.host_fragment)
                    if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.mainfragment) {
                        //当前界面不是主页，那么直接调用返回
                        nav.navigateUp()
                    } else {
                        //主页
                        if (System.currentTimeMillis() - exitTime > 2000) {
                            ToastUtils.showShort("再按一次退出程序")
                            exitTime = System.currentTimeMillis()
                        } else {
                            ToastUtils.showShort("good bye")
                            finish()
                        }
                    }
                }
            })
        appViewModel.appColor.value?.let {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0)
        }
    }

    override fun createObserver() {
        appViewModel.appColor.observeInActivity(this) {
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0)
        }
    }

    override fun onNetworkStateChanged(netState: NetState) {
        super.onNetworkStateChanged(netState)
        if (netState.isSuccess) {
            ToastUtils.showLong("我特么终于有网了啊！")
        } else {
            ToastUtils.showLong("我他么怎么断网了")
        }
    }
}
